//
//  LeverSheetViewModel.swift
//  Exchange
//
//  Created by 孟祥群 on 2018/7/6.
//  Copyright © 2018年 common. All rights reserved.
//

import UIKit

class LeverSheetViewModel: BaseViewModel {
    var isMarketBool:Bool = true {
        didSet {
            curretSelectModel = isMarketBool ? markModel : limitModel
        }
    } //限价 false 市价 true
    
    var changePrice:Bool = false {
        didSet {
            curretSelectModel.bailInfo = self.calculateCash(model: curretSelectModel)
//            self.changePosition(model: curretSelectModel)
        }
    }
    
   
    var tradeInfoModel:LeverTradeModel = LeverTradeModel()
    
    var curretSelectModel = LeverDataModel()
    var markModel:LeverDataModel = LeverDataModel()
    var limitModel:LeverDataModel = LeverDataModel()
    
    ///币种数组
    lazy var coninKidArray:Array<TradeCoinModel> = {
        let array:Array<TradeCoinModel> = []
        return array
    }()
    var tradeModel:TradeCoinModel = TradeCoinModel() //目标币中的交易信息
    var sourceModel:TradeCoinModel = TradeCoinModel() //交易币种的交易信息
  
    
    
    func changeLeverModelInformation(model:LeverDataModel) {
        //处理杠杆倍数
        if tradeInfoModel.regularModel.leverageTimes.count != 0{
            model.bail = tradeInfoModel.regularModel.leverageTimes.components(separatedBy: ",")
        }
        model.buyPrice = tradeInfoModel.buyPrice
        model.sellPrice = tradeInfoModel.sellPrice
        model.coinPair = tradeInfoModel.coinPair
        self.coinNumber()
        //获取限价价格
        let priceNumber = self.archiveDigitNumber(model: model, isNumber: false, isLimitPrice: true)
        model.price = (model.isBuyBool ? CYCalculate.cy_intercept(number: tradeInfoModel.buyPrice, digit: priceNumber) : CYCalculate.cy_intercept(number: tradeInfoModel.sellPrice, digit: priceNumber))!
        
        if model.isBuyBool && isMarketBool && !model.isEqual(limitModel) {
            model.number = ""
            model.lowNumber = 0
        }else {
            let tradeNumber = self.archiveDigitNumber(model: model, isNumber: true, isLimitPrice:false)
            model.number = CYCalculate.cy_intercept(number: tradeInfoModel.regularModel.minQty, digit: tradeNumber, isCover: false)!
            model.lowNumber = tradeInfoModel.regularModel.minQty
        }
        //处理价格小数 步长
        if tradeInfoModel.regularModel.minPrice != 0 {
            model.priceDigit = (CYCalculate.cy_intercept(number: tradeInfoModel.regularModel.minPrice, digit: 8, isCover: false)?.components(separatedBy: ".").count)!
        }
        
        //处理数量小数步长
        if tradeInfoModel.regularModel.minQty != 0 {
            model.numDigit = (CYCalculate.cy_intercept(number: tradeInfoModel.regularModel.minQty, digit: 8, isCover: false)?.components(separatedBy: ".").count)!
        }
        model.profitScales = "50"
        model.lossScales = "50"
        //获取币种资产
        model.coinAsset = tradeInfoModel.coinAssetModel.currentAmount
        //保证金描述
        model.bailInfo = self.calculateCash(model: model)
    }
    
    
    
    /// 获取止损描述
    ///
    /// - Returns: 描述
    func archiLossInfor(model:LeverDataModel) {
        let name:String = model.isBuyBool ? model.coinPair.components(separatedBy: "/").last! : model.coinPair.components(separatedBy: "/").first!
        if model.price == "" {
            model.stopLoss = ""
            model.stopLossInfo = String(format: "≤%@ %@ %@%@","0",kText("预计亏损"),"0",name)
            return
        }
        let price:Double = Double(model.price)!
        if price == 0.00 {
            model.stopLoss = ""
            model.stopLossInfo = String(format: "≤%@ %@ %@%@","0",kText("预计亏损"),"0",name)
            return
        }
        let tradeNumber = self.archiveDigitNumber(model: model, isNumber: false, isLimitPrice:false)
//        if !isMarketBool {
//            model.stopLoss = CYCalculate.cy_intercept(number: price * 0.5, digit: tradeNumber)!
//        }
        
        model.limitloss = price * 0.9
        let limitPrice = CYCalculate.cy_intercept(number: model.limitloss, digit: tradeNumber)
        let coinMoney = CYCalculate.cy_dividing(firstNumber: model.limitloss, lastNumber:price, digit: tradeNumber)
        model.stopLossInfo = String(format: "≤%@ %@ %@%@",limitPrice!,kText("预计亏损"),coinMoney,name)
    }
    
    /// 获取止盈描述
    ///
    /// - Returns:
    func archiveProfitInfor(model:LeverDataModel) {
        let name:String = model.isBuyBool ? model.coinPair.components(separatedBy: "/").last! : model.coinPair.components(separatedBy: "/").first!
        if model.price == "" {
            model.stopProfit = ""
            model.stopProfitInfo = String(format: "≤%@ %@ %@%@","0",kText("预计盈利"),"0",name)
            return
        }
        let price:Double = Double(model.price)!
        if price == 0.00 {
            model.stopProfit = ""
            model.stopProfitInfo = String(format: "≤%@ %@ %@%@","0",kText("预计盈利"),"0",name)
            return
        }
        let tradeNumber = self.archiveDigitNumber(model: model, isNumber: false, isLimitPrice:false)
//        if !isMarketBool {
//            model.stopProfit = CYCalculate.cy_intercept(number: price * 1.5, digit: tradeNumber)!
//        }
        model.limitProfit = price * 1.1
        let limitPrice = CYCalculate.cy_intercept(number: model.limitProfit, digit: tradeNumber)
        let coinMoney = CYCalculate.cy_dividing(firstNumber: model.limitloss, lastNumber:price, digit: tradeNumber)
        model.stopProfitInfo =  String(format: "≥%@ %@ %@%@",limitPrice!,kText("预计盈利"),coinMoney,name)
    }
    
    func archivePairName(model:LeverDataModel) -> String{
        //市价买入特殊处理
        if model.isBuyBool && model.isEqual(markModel){
            return model.coinPair.components(separatedBy: "/").last!
        }
        if curretSelectModel.isBuyBool {
            return model.coinPair.components(separatedBy: "/").last!
        }else {
            return model.coinPair.components(separatedBy: "/").first!
        }
        
    }
    
    
    /// 计算保证金
    ///
    /// - Parameter model: 当前操作的model 市价/限价
    /// - Returns: 描述
    func calculateCash(model:LeverDataModel) -> String {
        if model.number.count == 0 {
            model.tradePrice = 0
            model.coinPrice = "0"
            model.tradeName = String(format:"0 %@",self.archivePairName(model:model))
            return String(format:"0 %@",self.archivePairName(model:model))
        }
        if !isMarketBool && model.price.count == 0 {
            model.tradePrice = 0
            model.coinPrice = "0"
            model.tradeName = String(format:"0 %@",self.archivePairName(model:model))
            return String(format:"0 %@",self.archivePairName(model:model))
        }
        
        var price:Double = 0.00
        
        //限价 买入 计算保证金
        if model.isBuyBool && model.isEqual(limitModel){
            price = Double(model.price)! * Double(model.number)!
        }else {
            price = Double(model.number)!
        }
        //获取当前交易币种名称
        let name = self.archivePairName(model: model)
        //获取币币对法币的单价 计算支付的价格
        let money =  AppContext.default.archiveLegalPrice(coinKind: AppCacheInfo.default.currency, legalKind: name.count != 0 ? name : "")
        let tradeNumber = self.archiveDigitNumber(model: model, isNumber: false, isLimitPrice:false)
        //根据杠杆倍数计算 支付的价格
        if model.bail.count > model.selectIndex {
            let cash = CYCalculate.cy_dividing(firstNumber: price, lastNumber: model.bail[model.selectIndex].count != 0 ? model.bail[model.selectIndex] : "0", digit: tradeNumber,isNeedUp: true)
            model.tradePrice = Double(cash)!
            let currentMoney = CYCalculate.cy_multiplying(firstNumber: money, lastNumber: model.tradePrice, digit: 2)
            model.coinPrice = currentMoney
            model.tradeName = String(format:"%@ %@",cash,name)
            return String(format:"%@ %@",cash,name)
        }else {
            model.coinPrice = "0"
            model.tradeName = String(format:"%@ %@","0",name)
            return String(format:"%@ %@","0",name)
        }
    }
    
    
    /// 修改止损止盈
    func changePosition(model:LeverDataModel) {
        let tradeNumber = self.archiveDigitNumber(model: model, isNumber: false, isLimitPrice:false)
        //处理止盈止损
        if model.tradePrice != 0.00{
            //保证金的0.5 1.5倍
            let kPrice = CYCalculate.cy_intercept(number: model.tradePrice * 0.5, digit: tradeNumber)!
            let yPrice = CYCalculate.cy_intercept(number: model.tradePrice * 1.5, digit: tradeNumber)!
            
            if model.isEqual(markModel) && model.isBuyBool {
                let number = Double(model.price)!
               let chatNumber =  CYCalculate.cy_dividing(firstNumber: kPrice, lastNumber: number, digit: tradeNumber)
                let prifitNumber =  CYCalculate.cy_dividing(firstNumber: yPrice, lastNumber: number, digit: tradeNumber)
                model.stopLoss = CYCalculate.cy_minus(firstNumber: model.buyPrice, lastNumber: chatNumber, digit: tradeNumber)
                model.stopProfit = CYCalculate.cy_add(firstNumber: model.buyPrice, lastNumber: prifitNumber, digit: tradeNumber)
            }else if model.isEqual(markModel) && !model.isBuyBool {
                let amount = CYCalculate.cy_multiplying(firstNumber: model.number, lastNumber: model.sellPrice, digit: tradeNumber)
                
                let cyNumber = CYCalculate.cy_minus(firstNumber: model.number, lastNumber: model.tradePrice, digit: tradeNumber)
                let pair = CYCalculate.cy_add(firstNumber: kPrice, lastNumber: cyNumber, digit: tradeNumber)
                
                let profitPair = CYCalculate.cy_add(firstNumber: yPrice, lastNumber: cyNumber, digit: tradeNumber)
                model.stopLoss = CYCalculate.cy_dividing(firstNumber: amount, lastNumber: pair, digit: tradeNumber)
                model.stopProfit = CYCalculate.cy_dividing(firstNumber: amount, lastNumber: profitPair, digit: tradeNumber)
                
                
            }else if model.isBuyBool {
                let current = model.buyPrice
//                let lossPrice = Double(kPrice)! / Double(model.number)!
                let lossPrice = CYCalculate.cy_dividing(firstNumber: kPrice, lastNumber: model.number, digit: 8)
                model.stopLoss = CYCalculate.cy_minus(firstNumber: current, lastNumber: lossPrice, digit: tradeNumber)
                
                let profitPrice = CYCalculate.cy_dividing(firstNumber: yPrice, lastNumber: model.number, digit: 8)
                model.stopProfit = CYCalculate.cy_minus(firstNumber: current, lastNumber: profitPrice, digit: tradeNumber)
                
//                model.stopLoss = CYCalculate.cy_dividing(firstNumber: Double(amount)!, lastNumber: Double(pair)!, digit: tradeNumber)
//                model.stopProfit = CYCalculate.cy_dividing(firstNumber: Double(amount)!, lastNumber: Double(profitPair)!, digit: tradeNumber)
                
            }else {
                let amount = CYCalculate.cy_multiplying(firstNumber: model.number, lastNumber: model.sellPrice, digit: tradeNumber)
                
                let cyNumber = CYCalculate.cy_minus(firstNumber: model.number, lastNumber: model.tradePrice, digit: tradeNumber)
                let pair = CYCalculate.cy_add(firstNumber: kPrice, lastNumber: cyNumber, digit: tradeNumber)
                
                let profitPair = CYCalculate.cy_add(firstNumber: yPrice, lastNumber: cyNumber, digit: tradeNumber)
                model.stopLoss = CYCalculate.cy_dividing(firstNumber: amount, lastNumber: pair, digit: tradeNumber)
                model.stopProfit = CYCalculate.cy_dividing(firstNumber: amount, lastNumber: profitPair, digit: tradeNumber)
            }
            
            
        }else {
            model.stopLoss = ""
            model.stopProfit = ""
        }
        //处理止损止盈
        self.archiLossInfor(model: model)
        self.archiveProfitInfor(model: model)
    }
    
    
    /// 数量添加处理
    ///
    /// - Parameter addBool: + -
    /// - Returns: 结果
    func leverNumberChange(addBool:Bool) -> String {
        if curretSelectModel.number.count == 0 {
            curretSelectModel.number = "0"
        }
        let tradeNumber = self.archiveDigitNumber(model: curretSelectModel, isNumber: true, isLimitPrice:false)
        if addBool {
            curretSelectModel.number = CYCalculate.cy_add(firstNumber: curretSelectModel.number, lastNumber: tradeInfoModel.regularModel.stepSize, digit: tradeNumber)
        }else {
            if CYCalculate.campare(firstNumber: Double(curretSelectModel.number)!, lastNumber: tradeInfoModel.regularModel.stepSize)
                != .small {
                curretSelectModel.number = CYCalculate.cy_minus(firstNumber: curretSelectModel.number, lastNumber: tradeInfoModel.regularModel.stepSize, digit: tradeNumber)
                
                if CYCalculate.campare(firstNumber: Double(curretSelectModel.number)!, lastNumber: tradeInfoModel.regularModel.minQty) == .small {
                    curretSelectModel.number = CYCalculate.cy_intercept(number: tradeInfoModel.regularModel.minQty, digit: tradeNumber, isCover: false)!
                }
            }else {
                curretSelectModel.number = CYCalculate.cy_intercept(number: tradeInfoModel.regularModel.minQty, digit: tradeNumber, isCover: false)!
            }
        }
        return curretSelectModel.number
    }
    
    /// 限价价格处理
    ///
    /// - Parameter addBool: + -
    /// - Returns: 结果
    func leverPriceChange(addBool:Bool) -> String {
        let tradeNumber = self.archiveDigitNumber(model: curretSelectModel, isNumber: false, isLimitPrice:true)
        curretSelectModel.price = curretSelectModel.price.count == 0 ? "0" : curretSelectModel.price
        if addBool {
            curretSelectModel.price = CYCalculate.cy_add(firstNumber: curretSelectModel.price, lastNumber: tradeInfoModel.regularModel.tickSize, digit: tradeNumber)
        }else {
            if CYCalculate.campare(firstNumber: Double(curretSelectModel.price)!, lastNumber: tradeInfoModel.regularModel.tickSize)
                != .small {
                curretSelectModel.price = CYCalculate.cy_minus(firstNumber: curretSelectModel.price, lastNumber: tradeInfoModel.regularModel.tickSize, digit: tradeNumber)
            }else {
                CYMBShow.showMessage(kText("价格计算错误"))
            }
        }
        
        return curretSelectModel.price
    }
    
    
    
    /// 触发止损
    ///
    /// - Parameter addBool: + -
    /// - Returns: 结果
    func leverLossChange(addBool:Bool) -> String {
        let tradeNumber = self.archiveDigitNumber(model: curretSelectModel, isNumber: false, isLimitPrice:false)
        curretSelectModel.stopLoss = curretSelectModel.stopLoss.count == 0 ? "0" : curretSelectModel.stopLoss
        if addBool {
            curretSelectModel.stopLoss = CYCalculate.cy_add(firstNumber: curretSelectModel.stopLoss, lastNumber: tradeInfoModel.regularModel.tickSize, digit: tradeNumber)
            if CYCalculate.campare(firstNumber: Double(curretSelectModel.stopLoss)!, lastNumber: curretSelectModel.limitloss) == .larget {
                curretSelectModel.stopLoss = CYCalculate.cy_intercept(number: curretSelectModel.limitloss, digit: tradeNumber)!
            }
        }else {
            if CYCalculate.campare(firstNumber: Double(curretSelectModel.stopLoss)!, lastNumber: tradeInfoModel.regularModel.tickSize)
                != .small {
                curretSelectModel.stopLoss = CYCalculate.cy_minus(firstNumber: curretSelectModel.stopLoss, lastNumber: tradeInfoModel.regularModel.tickSize, digit: tradeNumber)
            }else {
                CYMBShow.showMessage(kText("触发止损计价错误"))
            }
        }
        
        return curretSelectModel.stopLoss
    }
    
    //触发止盈
    func leverProfitChange(addBool:Bool) -> String {
        let tradeNumber = self.archiveDigitNumber(model: curretSelectModel, isNumber: false, isLimitPrice:false)
        curretSelectModel.stopProfit = curretSelectModel.stopProfit.count == 0 ? "0" : curretSelectModel.stopProfit
        if addBool {
            curretSelectModel.stopProfit = CYCalculate.cy_add(firstNumber: curretSelectModel.stopProfit, lastNumber: tradeInfoModel.regularModel.tickSize, digit: tradeNumber)
        }else {
            if CYCalculate.campare(firstNumber: Double(curretSelectModel.stopProfit)!, lastNumber: tradeInfoModel.regularModel.tickSize)
                == .larget {
                curretSelectModel.stopProfit = CYCalculate.cy_minus(firstNumber: curretSelectModel.stopProfit, lastNumber: tradeInfoModel.regularModel.tickSize, digit: tradeNumber)
            }else {
                curretSelectModel.stopProfit = CYCalculate.cy_intercept(number: curretSelectModel.limitProfit, digit: tradeNumber)!
            }
        }
        
        return curretSelectModel.stopProfit
    }
    
    /// 获取资产
    ///
    /// - Returns: 币种对应的数量
    func coinNumber(){
        tradeInfoModel.coinAssetModel  = AssetModel()
        if tradeInfoModel.coinPair.components(separatedBy: "/").count > 1 {
            var name = ""
            if isMarketBool && curretSelectModel.isBuyBool {
                name = tradeInfoModel.coinPair.components(separatedBy: "/").last!
            }else {
                name =  (!curretSelectModel.isBuyBool ? tradeInfoModel.coinPair.components(separatedBy: "/").first :
                    tradeInfoModel.coinPair.components(separatedBy: "/").last)!
            }
            for model in tradeInfoModel.dateArr {
                if model.coinCode == name {
                    tradeInfoModel.coinAssetModel = model
                }
            }
        }
    }
    
    /// 匹配币对币种的交易信息
    func changeTradeInfo() {
       let sourceCoin = tradeInfoModel.coinPair.components(separatedBy: "/").last!
       let tradeCoin = tradeInfoModel.coinPair.components(separatedBy: "/").first!
        for model in coninKidArray {
            if model.coinCode == sourceCoin {
                sourceModel = model
            }
            if model.coinCode == tradeCoin {
                tradeModel = model
            }
        }
    }
    
    /// 获取不同币种截位的单位
    ///
    /// - Parameters:
    ///   - isNumber: 是否是数量
    ///   - isLimitPrice: 是否是限价价格
    /// - Returns: 结果
    func archiveDigitNumber(model:LeverDataModel,isNumber:Bool,isLimitPrice:Bool = false) -> Int{
        if model.isEqual(markModel) && model.isBuyBool {
            return tradeInfoModel.regularModel.priceDigit
        }
        if model.isBuyBool {
            if isNumber {
                return tradeInfoModel.regularModel.numberdigit 
            }else {
                return tradeInfoModel.regularModel.priceDigit
            }
        }else {
            if isLimitPrice {
                return tradeInfoModel.regularModel.priceDigit
            }else {
                return tradeInfoModel.regularModel.numberdigit
            }
        }
    }
    
    func checkStates() -> Bool {
        if curretSelectModel.number.count == 0 {
            CYMBShow.showMessage("请输入交易个数")
            return false
        }
        
        if !self.isMarketBool {
            if curretSelectModel.price.count == 0  {
                CYMBShow.showMessage("请输入单价")
                return false
            }
            if Double(curretSelectModel.price)! == 0.00 {
                CYMBShow.showMessage("交易单价不能为0")
                return false
            }
            if Double(curretSelectModel.price)! < tradeInfoModel.regularModel.minPrice {
                CYMBShow.showMessage("当前单价不能低于最低委托价")
                return false
            }
            
            if tradeInfoModel.regularModel.maxPrice != 0.00 {
                if Double(curretSelectModel.price)! > tradeInfoModel.regularModel.maxPrice {
                    CYMBShow.showMessage(kText("交易单价不能大于最高单价"))
                    return false
                }
            }
            ///判断上下幅度
            if tradeInfoModel.regularModel.increase != 0.0 {
                if curretSelectModel.isBuyBool {
                    let maxPrice = Double(curretSelectModel.price)! * (1 + tradeInfoModel.regularModel.increase/100)
                    if Double(curretSelectModel.price)! > maxPrice  {
                        CYMBShow.showMessage("买入单价不能高于最大值")
                        return false
                    }
                }else {
                    let minPrice = Double(curretSelectModel.price)! * (1 - tradeInfoModel.regularModel.increase/100)
                    if Double(curretSelectModel.price)! < minPrice  {
                        CYMBShow.showMessage("卖出单价不能低于最低值")
                        return false
                    }
                    
                }
            }
//            let pyPrice =   CYCalculate.cy_minus(firstNumber: Double(curretSelectModel.price)!, lastNumber: tradeInfoModel.regularModel.minPrice, digit: 8)
            
//            let differenPrice = CYCalculate.cy_multiplying(firstNumber: Double(pyPrice)!, lastNumber: 100000000.00, digit: 8)
//            let regualrPrice = Double(differenPrice)!.truncatingRemainder(dividingBy: tradeInfoModel.regularModel.tickSize)
//            if regualrPrice != 0.00 {
//                CYMBShow.showMessage("当前单价不符合交易规则,请重新输入")
//                return false
//            }
            
            if Double(curretSelectModel.number)! < tradeInfoModel.regularModel.minQty {
                CYMBShow.showMessage("当前数量不能低于最低交易数量")
                return false
            }
            
//            let differenNumber = (Double(curretSelectModel.number)! - tradeInfoModel.regularModel.minQty) * 100000000
//            let regualrNumber = differenNumber.truncatingRemainder(dividingBy:tradeInfoModel.regularModel.stepSize)
//            if regualrNumber != 0.00 {
//                CYMBShow.showMessage("当前数量不符合交易规则,请重新输入")
//                return false
//            }
        }
        
        if curretSelectModel.tradePrice > tradeInfoModel.coinAssetModel.currentAmount {
            CYMBShow.showMessage("可用保证金不足")
            return false
        }
        
        if !(curretSelectModel.bail.count > curretSelectModel.selectIndex) {
            CYMBShow.showMessage("杠杆选择错误")
            return false
        }
        return true
    }
    
    
}
